﻿using ChoMy.Areas.Admin.Models;
using ChoMy.Constants;
using ChoMy.Helpers;
using ChoMy.Models;
using ChoMy.Models.Data;
using PagedList;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;

namespace ChoMy.Areas.Admin.Controllers
{
    public class PostController : Controller
    {
        private ChoMyContext db = new ChoMyContext();
        private StringHelper stringHelper = new StringHelper();
        private string title = "bài đăng";

        public PostController()
        {
            ViewBag.Title = title;
        }

        [Authorize(Roles = "Admin, Read Post")]
        public ActionResult Index(bool? isTrash, string search, string sortOrder, int? page, int? pageSize)
        {
            var sortList = new List<string> { "Name", "DateModified", "DateCreated" };
            var pageSizeList = new List<int> { 10, 25, 50, 100 };
            int pageNumber = page ?? 1;

            pageSize = pageSize ?? 10;
            sortOrder = sortOrder ?? "DateCreated_desc";
            isTrash = isTrash ?? false;

            ViewBag.IsTrash = isTrash;
            ViewBag.PageSize = pageSize;
            ViewBag.PageSizeDDL = new SelectList(pageSizeList, pageSize);
            ViewBag.ReturnListUrl = Request.Url.AbsoluteUri;

            IQueryable<Post> query = db.Posts;

            ViewBag.TrashCount = query.Count(x => x.IsDelete);
            ViewBag.ListCount = query.Count(x => !x.IsDelete);

            if (!String.IsNullOrWhiteSpace(search))
            {
                page = 1;

                query = Search(query, search.Trim());
            }

            query = Sort(query, sortOrder, sortList);

            query = query.Where(x => x.IsDelete == isTrash);

            return View(query.ToPagedList(pageNumber, (int)pageSize));
        }

        [Authorize(Roles = "Admin, Read Post")]
        public ActionResult Details(int id, string partialView = "_Details")
        {
            Post post = db.Posts.Find(id);

            return PartialView(partialView, post);
        }

        [Authorize(Roles = "Admin, Create Post")]
        public ActionResult Create(string returnListUrl)
        {
            ViewBag.ReturnListUrl = returnListUrl;

            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Create Post")]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Create(PostCreator model, string returnListUrl)
        {
            if (ModelState.IsValid)
            {
                var post = new Post();
                post.Name = model.Name.Trim();
                post.Description = model.Description;

                db.Posts.Add(post);
                db.SaveChanges();

                SaveHistory("Create", post.Name);
                AlertHandling("Create", post.Name);

                if (!String.IsNullOrWhiteSpace(returnListUrl))
                {
                    return Redirect(returnListUrl);
                }

                return RedirectToAction("Index");
            }

            ViewBag.ReturnListUrl = returnListUrl;

            return View(model);
        }

        [Authorize(Roles = "Admin, Edit Post")]
        public ActionResult Edit(int? id, string returnListUrl)
        {
            if (id == null)
            {
                return RedirectToAction("BadRequest", "Error");
            }

            Post post = db.Posts.Find(id);

            if (post == null)
            {
                return RedirectToAction("NotFound", "Error");
            }

            var model = new PostEditor();
            model.Id = post.Id;
            model.Name = post.Name;
            model.Description = post.Description;

            ViewBag.ReturnListUrl = returnListUrl;

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Edit Post")]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Edit(PostEditor model, string returnListUrl)
        {
            if (ModelState.IsValid)
            {
                Post post = db.Posts.Find(model.Id);
                post.Name = model.Name.Trim();
                post.Description = model.Description;
                post.DateModified = DateTime.Now;
                post.ModifiedBy = User.Identity.Name;

                db.Entry(post).State = EntityState.Modified;
                db.SaveChanges();

                SaveHistory("Edit", post.Name);
                AlertHandling("Edit", post.Name);

                if (!String.IsNullOrWhiteSpace(returnListUrl))
                {
                    return Redirect(returnListUrl);
                }

                return RedirectToAction("Index");
            }

            ViewBag.ReturnListUrl = returnListUrl;

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Delete Without Recycle Post")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteWithoutRecycle(int id, string returnListUrl)
        {
            Post post = db.Posts.Find(id);

            string postName = post.Name;

            db.Posts.Remove(post);
            db.SaveChanges();

            SaveHistory("DeleteWithoutRecycle", postName);
            AlertHandling("DeleteWithoutRecycle", postName);

            if (!String.IsNullOrWhiteSpace(returnListUrl))
            {
                return Redirect(returnListUrl);
            }

            return RedirectToAction("Index", new { isTrash = true });
        }

        [HttpPost]
        [Authorize(Roles = "Admin, Delete Or Restore Post")]
        public ActionResult DeleteOrRestore(int id)
        {
            Post post = db.Posts.Find(id);

            post.IsDelete = post.IsDelete ? false : true;
            post.DateModified = DateTime.Now;
            post.ModifiedBy = User.Identity.Name;

            db.Entry(post).State = EntityState.Modified;
            db.SaveChanges();

            if(post.IsDelete)
            {
                SaveHistory("Delete", post.Name);
            }
            else
            {
                SaveHistory("Restore", post.Name);
            }

            return Json(post.IsDelete ? 1 : 0, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult CheckName(string name, int? id)
        {
            name = name.Trim();

            Post post = db.Posts.FirstOrDefault(x => x.Name == name && x.Id != id);

            if (post != null)
            {
                if (!post.IsDelete)
                {
                    string url = Url.Action("Index", new { search = name, isTrash = false });
                    string result = String.Format("Tên {0} này đã tồn tại. <a href='{1}'>Chi tiết</a>.", title, url);

                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    string url = Url.Action("Index", new { search = name, isTrash = true });
                    string result = String.Format("Tên {0} này đã tạm thời bị xóa. <a href='{1}'>Chi tiết</a>.", title, url);

                    return Json(result, JsonRequestBehavior.AllowGet);
                }
            }

            return Json(true, JsonRequestBehavior.AllowGet);
        }

        #region Helpers
        private void SaveHistory(string crud, string name)
        {
            string type = "Post";

            DateTime dateTime = DateTime.Now;
            string userName = User.Identity.Name;
            string description = "";

            switch(crud)
            {
                case "Create":
                    description = String.Format("<b>{0}</b> tạo mới {1} <b>{2}</b>", userName, title, name);
                    break;
                case "Edit":
                    description = String.Format("<b>{0}</b> chỉnh sửa {1} <b>{2}</b>", userName, title, name);
                    break;
                case "DeleteWithoutRecycle":
                    description = String.Format("<b>{0}</b> xóa vĩnh viễn {1} <b>{2}</b>", userName, title, name);
                    break;
                case "Delete":
                    description = String.Format("<b>{0}</b> xóa tạm thời {1} <b>{2}</b>", userName, title, name);
                    break;
                case "Restore":
                    description = String.Format("<b>{0}</b> khôi phục {1} <b>{2}</b>", userName, title, name);
                    break;
            }

            var history = new History();
            history.DateTime = dateTime;
            history.Description = description;
            history.HistoryTypeId = db.HistoryTypes.First(x => x.Name == type).Id;

            db.Histories.Add(history);
            db.SaveChanges();
        }

        private void AlertHandling(string crud, string name)
        {
            string userName = User.Identity.Name;
            string alertMessage = "";

            switch (crud)
            {
                case "Create":
                    alertMessage = String.Format("Bạn vừa tạo mới {0}: <b>{1}</b>", title, name);
                    break;
                case "Edit":
                    alertMessage = String.Format("Bạn vừa chỉnh sửa {0}: <b>{1}</b>", title, name);
                    break;
                case "DeleteWithoutRecycle":
                    alertMessage = String.Format("Bạn vừa xóa vĩnh viễn {0}: <b>{1}</b>", title, name);
                    break;
            }

            if (!String.IsNullOrWhiteSpace(alertMessage))
            {
                Session["alert-message-" + userName] = alertMessage;
                Session["alert-type-" + userName] = "alert-success";
            }            
        }

        private IQueryable<Post> Search(IQueryable<Post> query, string search)
        {
            ViewBag.Search = search;

            query = query.Where(x => x.Name.Contains(search));

            return query;
        }

        private IQueryable<Post> Sort(IQueryable<Post> query, string sortOrder, List<string> sortList)
        {
            ViewBag.SortOrder = sortOrder;

            foreach (string sort in sortList)
            {
                ViewData[sort + "Sort"] = sortOrder == sort + "_desc" ? sort : sort + "_desc";
            }

            if (sortOrder.Contains("_desc"))
            {
                sortOrder = sortOrder.Replace("_desc", "");
                query = query.OrderBy(sortOrder + " descending");
                ViewData[sortOrder + "Icon"] = DataTableConstant.DescSortIcon;
            }
            else
            {
                query = query.OrderBy(sortOrder);
                ViewData[sortOrder + "Icon"] = DataTableConstant.AscSortIcon;
            }

            return query;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }

            base.Dispose(disposing);
        }
        #endregion
    }
}